﻿using Newtonsoft.Json;
using PmSoft;
using PmSoft.Exceptions;

namespace ManagementApi.Services
{
    /// <summary>
    /// 微信相关服务
    /// </summary>
    [UseDI(ServiceLifetime.Scoped)]
    public class WeiXinService
    {
        private readonly IConfiguration configuration;
        /// <summary>
        /// 微信appid
        /// </summary>
        private string appId = "";
        /// <summary>
        /// 微信密钥
        /// </summary>
        private string appSecret = "";

        /// <summary>
        /// 微信服务构造方法
        /// </summary>
        /// <param name="configuration"></param>
        public WeiXinService(IConfiguration configuration)
        {
            this.configuration = configuration;
            appId = this.configuration.GetValue<string>("ThreePartyOptions:WeChat:AppID");
            appSecret = this.configuration.GetValue<string>("ThreePartyOptions:WeChat:AppSecret");
        }

        /// <summary>
        /// 获取token
        /// </summary>
        /// <returns></returns>
        /// <exception cref="BusinessException"></exception>
        public async Task<string> GetAccessToken()
        {
            string url = $"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={appId}&secret={appSecret}";

            using (HttpClient client = new HttpClient())
            {
                HttpResponseMessage response = await client.GetAsync(url);
                response.EnsureSuccessStatusCode();
                string responseBody = await response.Content.ReadAsStringAsync();

                // 解析响应数据获取token
                var responseObj = JsonConvert.DeserializeObject<dynamic>(responseBody);
                if (responseObj == null || responseObj.access_token == null)
                {
                    throw new BusinessException("token获取失败");
                }

                return responseObj.access_token;
            }
        }
        /// <summary>
        /// 微信登录获取openid
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public async Task<string> GetLogin(string code)
        {
            string openId = await GetOpenId(appId, appSecret, code);
            return openId;
        }

        /// <summary>
        /// 获取openid
        /// </summary>
        /// <param name="appId"></param>
        /// <param name="appSecret"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        /// <exception cref="BusinessException"></exception>
        public async Task<string> GetOpenId(string appId, string appSecret, string code)
        {
            string url = $"https://api.weixin.qq.com/sns/oauth2/access_token?appid={appId}&secret={appSecret}&code={code}&grant_type=authorization_code";

            using (HttpClient client = new HttpClient())
            {
                HttpResponseMessage response = await client.GetAsync(url);
                response.EnsureSuccessStatusCode();
                string responseBody = await response.Content.ReadAsStringAsync();

                // 解析响应数据获取openid
                var responseObj = JsonConvert.DeserializeObject<dynamic>(responseBody);
                if (responseObj == null || responseObj.openid == null)
                {
                    throw new BusinessException("openid获取失败");
                }
                return responseObj.openid;
            }
        }
    }
}
